'use strict';


const appId = 'wx88538170a82c067b'
const appSecret = '5ad032ae3a91448f4aed71e588947522'
const {
	getToken,
	verifyToken
} = require("wx-common")
const db = uniCloud.database()
const user = db.collection('user_data')
exports.main = async (event, context) => {
	const res = await uniCloud.httpclient.request(
		"https://api.weixin.qq.com/sns/jscode2session?appid=" + appId + "&secret=" + appSecret +
		"&js_code=" +
		event.code + "&grant_type=authorization_code", {
			dataType: "json"
		}
	)
	if (res.status === 200) {
		const wx_openid = res.data.openid
		const wx_session_key = res.data.session_key
		// 生成token
		const token = getToken(wx_openid)
		//查询数据库判断用户是否已经注册 根据openid查找
		const res_user = await user.where({
			openid: wx_openid
		}).get()
		//用户未注册存储用户信息
		if (res_user.data && res_user.data.length === 0) {
			user.add({
				avatarUrl: event.avatarUrl,
				nickName: event.nickName,
				gender: event.gender,
				openid: wx_openid,
				session_key: wx_session_key,
				mobile: "",
				token: token,
				age: null,
				height: null,
				weight: null,
				targetWeight: null,
				metabolize: null,
				signature: '',
				carbohydrate: null,
				protein: null,
				fat: null
			})
		} else {
			//用户已经存在更新token和session_key
			user.where({
				openid: wx_openid
			}).update({
				session_key: wx_session_key,
				token: token
			})
		}
		//将需要的个人信息返回到客户端例如:头像 昵称 等
		return user.where({
			openid: wx_openid
		}).field({
			avatarUrl: true,
			gender: true,
			nickName: true,
			mobile: true,
			token: true,
		}).get()
	}




	//返回数据给客户端
	return {
		code: 200,
		msg: "登录成功",
		data: {
			userData,
			token
		}
	}
};